package com.emm.yixun.website.common.utils.security;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.emm.yixun.common.model.User;
import com.emm.yixun.website.common.utils.base.Const;

/**
 * 封装shiro用对象获取
 * 
 */
public class ShiroUtil {
	/**
	 * 获取当前对象的拷贝
	 * 
	 * @return
	 */
	public static User getCurrentUser() {
		User user = null;
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		if(null==session)return user;
		Object obj = session.getAttribute(Const.SESSION_USER);
		if(null==obj)return user;
		/**
		 * 复制一份对象，防止被错误操作
		 */
		try {
			user = (User) BeanUtils.cloneBean((User)obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	
	/**
	 * 获取数据权限资源
	 * 
	 * @return
	 */
	public static String getDataPermissionResources(String resourcesName) {
		if(StringUtils.isNotEmpty(resourcesName)){
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession();
			Object object = session.getAttribute(resourcesName);
			return object == null?"":object.toString();
		}else{
			return null;
		}
		
	}
	
	/**
	 * 设置数据权限资源
	 * 
	 * @return
	 */
	public static void setDataPermissionResources(String resourcesName, String resourcesCode) {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		session.setAttribute(resourcesName, resourcesCode);
	}
}
